﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections;
using System.Collections.Generic;

namespace Fall.HttpClient
{
    /// <summary>
    /// 注入HttpClient客户端
    /// </summary>
    public static class FallHttpClientExtensions
    {
        /// <summary>
        /// 注入单个客户端
        /// </summary>
        /// <param name="services"></param>
        /// <param name="name"></param>
        /// <param name="uri"></param>
        /// <returns></returns>
        public static void AddFallHttpClient(this IServiceCollection services,string name,Uri uri) 
        {
            services.AddHttpClient(name,config=> 
            {
                config.BaseAddress = uri;
            });
        }

        /// <summary>
        /// 注入多个客户端。
        /// 基于配置，从Configuration的"Fall:HttpClient"节点读取所有的键值对。
        /// 键的名称是Client的名称，值的名称是BaseAddress。
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        public static void AddFallHttpClient(this IServiceCollection services,IConfiguration configuration)
        {
            var value = configuration.GetSection("Fall").GetSection("HttpClient").AsEnumerable();
            foreach (var item in value)
            {
                services.AddFallHttpClient(item.Key, new Uri(item.Value));
            }
        }
        /// <summary>
        /// 注入多个客户端。
        /// </summary>
        /// <param name="services"></param>
        /// <param name="keyValues"></param>
        public static void AddFallHttpClient(this IServiceCollection services,IEnumerable<KeyValuePair<string,Uri>> keyValues) 
        {
            foreach (var item in keyValues)
            {
                services.AddFallHttpClient(item.Key,item.Value);
            }
        }
        /// <summary>
        /// 注入HttpClient服务
        /// </summary>
        /// <param name="services"></param>
        public static void AddFallHttpClient(this IServiceCollection services) 
        {
            services.AddHttpClient();
        }

        /// <summary>
        /// 注入默认的Http请求前做的任务
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddFallPreHttp(this IServiceCollection services)
        {
            return services.AddTransient<HttpContextMiddleware>().AddHttpContextAccessor();
        }
    }
}
